#include "SList.h"

void SLTPrint(SLTNode* phead)
{
	SLTNode* pcur = phead;
	while (pcur)
	{
		printf("%d->", pcur->data);
		pcur = pcur->next;
	}
	printf("NULL");
}

SLTNode* SLTBuyNode(SLTDataType x)
{
	SLTNode* Node = (SLTNode*)malloc(sizeof(SLTNode));
	if (Node == NULL)
	{
		perror("malloc fail!");
		exit(1);
	}
	Node->data = x;
	Node->next = NULL;

	return Node;
}


void SLTPushBack(SLTNode** pphead, SLTDataType x)
{
	assert(pphead);
	SLTNode* NewNode=SLTBuyNode(x);
	if (*pphead == NULL)
	{
		*pphead = NewNode;
	}
	else
	{
		SLTNode* pcur = *pphead;
		while (pcur->next)
		{
			pcur = pcur->next;
		}
		pcur->next = NewNode;
	}
}

void SLTPushFront(SLTNode** pphead, SLTDataType x)
{
	assert(pphead);
	SLTNode* NewNode = SLTBuyNode(x);
		NewNode->next = *pphead;
		*pphead = NewNode;
}

void SLTPopBack(SLTNode** pphead)
{
	assert(pphead && *pphead);

	if ((*pphead)->next == NULL)
	{
		free(*pphead);
		*pphead = NULL;
	}
	else
	{
		SLTNode* ptail = *pphead;
		SLTNode* prev = *pphead;
		while (ptail->next)
		{
			prev = ptail;
			ptail = ptail->next;
		}
		prev->next = NULL;
		free(ptail);
		ptail->next = NULL;
	}
}

void SLTPopFront(SLTNode** pphead)
{
	assert(pphead && *pphead);
	if ((*pphead)->next == NULL)
	{
		free(*pphead);
		*pphead = NULL;
	}
	else
	{
		SLTNode* next = (*pphead)->next;
		free(*pphead);
		*pphead = next;
	}
}

SLTNode* SLTFind(SLTNode* phead, SLTDataType x)
{
	assert(phead);
	SLTNode* pcur = phead;

	int count = 1;
	while (pcur)
	{
		if (pcur->data == x)
		{
			return pcur;
		}
		else 
		{
			pcur = pcur->next;
		}
	}
	return NULL;
}

void SLTInsert(SLTNode** pphead, SLTNode* pos, SLTDataType x)
{
	assert(pphead);
	assert(pos);
	SLTNode* InsertData=SLTBuyNode(x);
	SLTNode* prev = *pphead;

	if (pos == *pphead)
	{
		SLTPushFront(pphead,x);
	}
	else 
	{
		while (prev->next != pos)
		{
			prev = prev->next;
		}
		InsertData->next = pos;
		prev->next = InsertData;
	}
}

void SLTInsertAfter(SLTNode** pphead, SLTNode* pos, SLTDataType x)
{
	assert(pphead);
	assert(pos);
	SLTNode* InsertData = SLTBuyNode(x);
	SLTNode* prev = *pphead;
	if (pos == *pphead)
	{
		SLTPushFront(pphead, x);
	}
	else
	{
		while (prev != pos)
		{
			prev = prev->next;
		}
		prev = prev->next;

		pos->next = InsertData;
		InsertData->next = prev;
	}
}

void SLTErase(SLTNode** pphead, SLTNode* pos)
{
	assert(pphead && *pphead);
	assert(pos);
	SLTNode* prev = *pphead;

	if (pos == *pphead)
	{
		SLTPopFront(pphead);
	}
	else
	{
		while (prev->next != pos)
		{
			prev = prev->next;
		}
		prev->next = prev->next->next;
		free(pos);
		pos = NULL;
	}
}

void SLTEraseAfter(SLTNode* pos)
{
	assert(pos);
	SLTNode* del = pos->next;
	pos->next= del->next;
	free(del);
	del = NULL;
}

void SListDestroy(SLTNode** pphead)
{
	assert(*pphead && pphead);
	SLTNode* prev = *pphead;
	while (prev)
	{
		SLTNode* next= prev->next;
		free(prev);
		prev=next;
	}
	*pphead = NULL;
}